package cn.cdut.yiwenqian.util;

import java.io.*;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


public class FtpUploadUtil {

	// ftp登录用户名
	private static final String USER_NAME = "yiwenqian";
	// ftp登录密码
	private static final String USER_PASSWORD = "admin";
	// ftp ip 地址
	private static final String SERVER_IP = "120.76.113.170";

	
	public void uploadFile(File file, String path) {
		FTPClient ftpClient = new FTPClient();
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			// 1.输入流
			InputStream is = new ByteArrayInputStream(buffer);
			// 2.连接服务器
			ftpClient.connect(SERVER_IP);
			// 3.登录ftp
			ftpClient.login(USER_NAME, USER_PASSWORD);
			// 4.指定写入的目录
			ftpClient.changeWorkingDirectory(path);
			// 5.写操作
			ftpClient.storeFile(file.getName(), is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * ftp下载数据
	 */
	public void downFile(String path,String localPath,String fileName) {
		
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			// 1.连接服务器
			ftp.connect(SERVER_IP);
			// 2.登录服务器 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(USER_NAME, USER_PASSWORD);
			// 3.判断登陆是否成功
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
			}
			// 4.指定要下载的目录
			ftp.changeWorkingDirectory(path);// 转移到FTP服务器目录
			// 5.遍历下载的目录
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				// 解决中文乱码问题，两次解码
				byte[] bytes = ff.getName().getBytes("iso-8859-1");
				String fn = new String(bytes, "utf8");
				if (fn.equals(fileName)) {
					// 6.写操作，将其写入到本地文件中
					File localFile = new File(localPath + ff.getName());
					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}
			ftp.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
	}

}